package processor

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"mass-user/commons/message"
	"mass-user/commons/user"
	"mass-user/commons/utils"
	"net"
)

type UserProcess struct {

}

func (u *UserProcess) Login(userId int64, pwd string) error {
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		fmt.Println("error =", err)
		return err
	}
	var msg message.Message
	msg.Type = message.LoginMessageType
	loginMsg := message.LoginMessage{
		UserId:   userId,
		Pwd:      pwd,
		UserName: "",
	}
	data, err := json.Marshal(loginMsg)
	if err != nil {
		fmt.Println("json.Marshal(loginMsg) error", err)
		return err
	}
	msg.Data = string(data)
	data, err = json.Marshal(msg)
	if err != nil {
		fmt.Println("json.Marshal(msg) error", err)
		return err
	}
	dataLen := uint32(len(data))
	var b [4]byte
	binary.BigEndian.PutUint32(b[:4], dataLen)
	n, err := conn.Write(b[:4])
	if n != 4 || err != nil {
		fmt.Println("发送失败")
		return err
	}
	conn.Write(data)
	//defer conn.Close()

	tf := &utils.Transfer{
		Conn: conn,
		Buf:  [8096]byte{},
	}
	msg, err= tf.ReadPkg()
	if err != nil {
		return err
	}
	var loginRes message.LoginResponseMessage
	err = json.Unmarshal([]byte(msg.Data),&loginRes)
	if loginRes.Code == 200{
		// 显示在线用户
		for _, value := range loginRes.Users{
			if int64(value) == userId{
				continue
			}
			fmt.Println("用户id：", value)
			user := &user.User{
				UserId:     value,
				Pwd:        "",
				UserName:   "",
				UserStatus: message.UserOnline,
			}
			UserOnlineMap[value] = user
		}

		go ServerProcessMes(conn)
		for{
			ShowMenu()
		}
	}else{
		fmt.Println(loginRes.Error)
	}
	return nil
}

func (u *UserProcess)Register(userId int, pwd, username string) error {
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		fmt.Println("error =", err)
		return err
	}
	var msg message.Message
	msg.Type = message.RegisterMessageType
	regMsg := message.RegisterMessage{
		User:user.User{
			UserId:   userId,
			Pwd:      pwd,
			UserName: username,
		},
	}
	data, err := json.Marshal(regMsg)
	if err != nil {
		fmt.Println("json.Marshal(regMsg) error", err)
		return err
	}
	msg.Data = string(data)
	data, err = json.Marshal(msg)
	if err != nil {
		fmt.Println("json.Marshal(msg) error", err)
		return err
	}
	dataLen := uint32(len(data))
	var b [4]byte
	binary.BigEndian.PutUint32(b[:4], dataLen)
	n, err := conn.Write(b[:4])
	if n != 4 || err != nil {
		fmt.Println("发送失败")
		return err
	}
	conn.Write(data)
	//defer conn.Close()
	tf := &utils.Transfer{
		Conn: conn,
		Buf:  [8096]byte{},
	}
	msg, err= tf.ReadPkg()
	if err != nil {
		return err
	}
	var regRes message.RegisterResponseMessage
	err = json.Unmarshal([]byte(msg.Data),&regRes)
	if regRes.Code == 200{
		fmt.Println("注册成功")
	}else{
		fmt.Println(regRes.Error)
	}
	return nil
}
